// 引入创建slice的方法
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 创建异步对象
export const addAsync = createAsyncThunk('yyy', () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, 1000)
  })
})

export default createSlice({
  name: 'todos',
  initialState: {
    list: [
      { id: 1, todoName: '哈哈', isDone: false },
      { id: 2, todoName: '呵呵', isDone: true },
    ],
    flag: false,
  },
  reducers: {
    // 添加todo
    addTodo(state, action) {
      // 获取任务名
      const todoName = action.payload

      // 创建任务对象
      const todo = {
        todoName,
        isDone: false,
        id: state.list.length ? state.list[state.list.length - 1].id + 1 : 1,
      }

      state.list.push(todo)
    },
  },

  extraReducers(builder) {
    builder.addCase(addAsync.pending, (state, action) => {
      // 异步开始,pending对应的回调会执行
      state.flag = true
    })

    builder.addCase(addAsync.fulfilled, (state, action) => {
      // 修改list的数据(增加任务对象)
      // 一会儿通过action对象传递过来的是任务名
      // 1. 获取任务名
      const todoName = action.meta.arg
      // 2. 根据任务名创建任务对象
      const todo = {
        todoName,
        isDone: false,
        id: state.list.length ? state.list[state.list.length - 1].id + 1 : 1,
      }
      // 3. 将任务对象添加到list中
      state.list.push(todo)
      state.flag = false
    })
  },
})
